<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>加密价格监控</title>
    <script src="https://unpkg.com/ant-design-vue@3.2.20/dist/antd.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/ant-design-vue@3.2.20/dist/antd.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen">
    <div id="app" class="min-h-screen">
        <div class="min-h-screen">
            <!-- 顶部导航栏 -->
            <header class="bg-white shadow-md">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div class="flex justify-between items-center h-16">
                        <div class="flex items-center">
                            <img src="https://www.svgrepo.com/show/530438/ddos-protection.svg" class="h-8 w-8 mr-2">
                            <span class="text-lg font-semibold text-gray-900">加密价格监控</span>
                        </div>
                        <nav class="hidden md:flex space-x-4">
                            <a href="prices.html" class="text-blue-600 hover:text-blue-800">价格监控</a>
                        </nav>
                    </div>
                </div>
            </header>

            <!-- 主要内容区域 -->
            <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                <div class="bg-white rounded-lg shadow-lg p-6">
                    <!-- 顶部操作栏 -->
                    <div class="flex justify-between items-center mb-6">
                        <div class="flex items-center space-x-4">
                            <h2 class="text-2xl font-bold text-gray-900">策略</h2>
                        </div>
                        <button onclick="showModal()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">
                            添加
                        </button>
                    </div>

                    <!-- 数据表格 -->
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">交易对</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最小值操作符</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最小告警值</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最大值操作符</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最大告警值</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">发送间隔</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                            </thead>
                            <tbody id="rulesTableBody" class="bg-white divide-y divide-gray-200">
                                <!-- 数据行将通过JavaScript动态插入 -->
                            </tbody>
                        </table>
                        <!-- 分页控件 -->
                        <div id="pagination" class="flex justify-between items-center mt-4">
                            <div class="flex space-x-2">
                                <button onclick="previousPage()" class="px-3 py-1 border rounded">上一页</button>
                                <span id="pageInfo" class="px-3 py-1">第 1 页</span>
                                <button onclick="nextPage()" class="px-3 py-1 border rounded">下一页</button>
                            </div>
                        </div>
                    </div>

                    <!-- 表单模态框 -->
                    <div id="ruleModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full">
                        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                            <div class="mt-3">
                                <h3 id="modalTitle" class="text-lg font-medium leading-6 text-gray-900 mb-4">添加规则</h3>
                                <form id="ruleForm">
                                    <input type="hidden" id="editingId">
                                    <div class="mb-4">
                                        <label class="block text-sm font-medium text-gray-700">交易对 <span class="text-red-500">*</span></label>
                                        <input type="text" id="symbol" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
                                    </div>

                                    <div class="mb-4">
                                        <label class="block text-sm font-medium text-gray-700">发送间隔 <span class="text-red-500">*</span></label>
                                        <select id="interval" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
                                            <option value="5m">5分钟</option>
                                            <option value="10m">10分钟</option>
                                            <option value="30m">30分钟</option>
                                            <option value="1h">1小时</option>
                                            <option value="2h">2小时</option>
                                            <option value="1d">1天</option>
                                        </select>
                                    </div>

                                    <div class="grid grid-cols-2 gap-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700">最小值操作符 <span class="text-red-500">*</span></label>
                                            <select id="minOperator" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
                                                <option value="<=">小于等于</option>
                                                <option value=">=">大于等于</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700">最小告警值 <span class="text-red-500">*</span></label>
                                            <input type="number" id="minValue" required step="0.00000001" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
                                        </div>
                                    </div>

                                    <div class="grid grid-cols-2 gap-4 mt-4">
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700">最大值操作符 <span class="text-red-500">*</span></label>
                                            <select id="maxOperator" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
                                                <option value="<=">小于等于</option>
                                                <option value=">=">大于等于</option>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700">最大告警值 <span class="text-red-500">*</span></label>
                                            <input type="number" id="maxValue" required step="0.00000001" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
                                        </div>
                                    </div>

                                    <div class="mt-4">
                                        <label class="block text-sm font-medium text-gray-700">邮箱模板 <span class="text-red-500">*</span></label>
                                        <textarea id="emailTemplate" required rows="4" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm"></textarea>
                                    </div>

                                    <div class="mt-4">
                                        <label class="block text-sm font-medium text-gray-700">目标邮箱集合 <span class="text-red-500">*</span></label>
                                        <textarea id="targetEmails" required rows="4" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm"></textarea>
                                    </div>

                                    <div class="mt-4">
                                        <label class="block text-sm font-medium text-gray-700">状态</label>
                                        <input type="checkbox" id="isEnabled" class="mt-1">
                                    </div>

                                    <div class="mt-4 flex justify-end space-x-2">
                                        <button type="button" onclick="closeModal()" class="px-4 py-2 bg-gray-200 text-gray-800 rounded-md">取消</button>
                                        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md">确定</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </main>

            <!-- 页脚 -->
<!--            <footer class="bg-white mt-8">-->
<!--                <div class="text-center text-gray-500 py-4">-->
<!--                    加密货币规则管理系统 ©2024 Created by Your Company-->
<!--                </div>-->
<!--            </footer>-->
        </div>
    </div>

    <!-- 移动端导航 -->
    <div class="md:hidden fixed bottom-0 left-0 right-0 bg-white shadow-lg p-2 flex justify-around">
        <a href="/prices.html" class="text-blue-600 hover:text-blue-800">价格监控</a>
    </div>

    <script>
        let currentPage = 1;
        const pageSize = 10;
        let totalPages = 1;

        // 获取规则列表
        async function fetchRules() {
            try {
                const response = await fetch(`/api/rules?page=${currentPage}&pageSize=${pageSize}`);
                const data = await response.json();
                renderRules(data.data);
                totalPages = Math.ceil(data.total / pageSize);
                updatePagination();
            } catch (error) {
                console.error('Error fetching rules:', error);
                alert('获取规则列表失败');
            }
        }

        // 渲染规则列表
        function renderRules(rules) {
            const tbody = document.getElementById('rulesTableBody');
            tbody.innerHTML = '';

            rules.forEach(rule => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">${rule.symbol}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${rule.minOperator}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${rule.minValue}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${rule.maxOperator}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${rule.maxValue}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${rule.interval}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${rule.isEnabled ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                            ${rule.isEnabled ? '启用' : '禁用'}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <button onclick="editRule(${JSON.stringify(rule).replace(/"/g, '&quot;')})" class="text-blue-600 hover:text-blue-800 mr-2">编辑</button>
                        <button onclick="confirmDelete(${rule.id})" class="text-red-600 hover:text-red-800">删除</button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }

        // 显示模态框
        function showModal() {
            document.getElementById('modalTitle').textContent = '添加规则';
            document.getElementById('editingId').value = '';
            document.getElementById('ruleForm').reset();
            document.getElementById('ruleModal').classList.remove('hidden');
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('ruleModal').classList.add('hidden');
        }

        // 编辑规则
        function editRule(rule) {
            document.getElementById('modalTitle').textContent = '编辑规则';
            document.getElementById('editingId').value = rule.id;
            document.getElementById('symbol').value = rule.symbol;
            document.getElementById('interval').value = rule.interval;
            document.getElementById('minOperator').value = rule.minOperator;
            document.getElementById('minValue').value = rule.minValue;
            document.getElementById('maxOperator').value = rule.maxOperator;
            document.getElementById('maxValue').value = rule.maxValue;
            document.getElementById('emailTemplate').value = rule.emailTemplate;
            const targetEmails = Array.isArray(rule.targetEmails) ? rule.targetEmails : [];
            document.getElementById('targetEmails').value = targetEmails.join('\n');
            document.getElementById('isEnabled').checked = rule.isEnabled;
            document.getElementById('ruleModal').classList.remove('hidden');
        }

        // 确认删除
        function confirmDelete(id) {
            if (confirm('确定要删除这条规则吗？')) {
                deleteRule(id);
            }
        }

        // 删除规则
        async function deleteRule(id) {
            try {
                const response = await fetch(`/api/rules/${id}`, {
                    method: 'DELETE',
                });
                if (response.ok) {
                    alert('删除成功');
                    fetchRules();
                } else {
                    throw new Error('删除失败');
                }
            } catch (error) {
                console.error('Error deleting rule:', error);
                alert('删除失败');
            }
        }

        // 表单提交处理
        document.getElementById('ruleForm').addEventListener('submit', async (e) => {
            e.preventDefault();

            // 验证表单
            const symbol = document.getElementById('symbol').value.trim();
            const interval = document.getElementById('interval').value;
            const minOperator = document.getElementById('minOperator').value;
            const minValue = document.getElementById('minValue').value;
            const maxOperator = document.getElementById('maxOperator').value;
            const maxValue = document.getElementById('maxValue').value;
            const emailTemplate = document.getElementById('emailTemplate').value.trim();
            const targetEmails = document.getElementById('targetEmails').value.split('\n').filter(Boolean);

            // 验证必填字段
            if (!symbol) {
                alert('请输入交易对');
                return;
            }
            if (!interval) {
                alert('请选择发送间隔');
                return;
            }
            if (!minOperator) {
                alert('请选择最小值操作符');
                return;
            }
            if (!minValue) {
                alert('请输入最小告警值');
                return;
            }
            if (!maxOperator) {
                alert('请选择最大值操作符');
                return;
            }
            if (!maxValue) {
                alert('请输入最大告警值');
                return;
            }
            if (!emailTemplate) {
                alert('请输入邮箱模板');
                return;
            }
            if (targetEmails.length === 0) {
                alert('请输入至少一个目标邮箱');
                return;
            }

            // 验证数值
            if (isNaN(parseFloat(minValue))) {
                alert('最小告警值必须是有效的数字');
                return;
            }
            if (isNaN(parseFloat(maxValue))) {
                alert('最大告警值必须是有效的数字');
                return;
            }

            const formData = {
                symbol,
                interval,
                minOperator,
                minValue: parseFloat(minValue),
                maxOperator,
                maxValue: parseFloat(maxValue),
                emailTemplate,
                targetEmails,
                isEnabled: document.getElementById('isEnabled').checked
            };

            const editingId = document.getElementById('editingId').value;
            const url = editingId ? `/api/rules/${editingId}` : '/api/rules';
            const method = editingId ? 'PUT' : 'POST';

            try {
                const response = await fetch(url, {
                    method,
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(formData),
                });

                if (response.ok) {
                    alert(editingId ? '更新成功' : '创建成功');
                    closeModal();
                    fetchRules();
                } else {
                    throw new Error('操作失败');
                }
            } catch (error) {
                console.error('Error saving rule:', error);
                alert('操作失败');
            }
        });

        // 分页控制
        function previousPage() {
            if (currentPage > 1) {
                currentPage--;
                fetchRules();
            }
        }

        function nextPage() {
            if (currentPage < totalPages) {
                currentPage++;
                fetchRules();
            }
        }

        function updatePagination() {
            document.getElementById('pageInfo').textContent = `第 ${currentPage} 页 / 共 ${totalPages} 页`;
        }

        // 初始加载
        fetchRules();
    </script>

    <style>
        .ant-table-thead > tr > th {
            background-color: #f8fafc !important;
        }
        .custom-table .ant-table-tbody > tr:hover > td {
            background-color: #f1f5f9 !important;
        }
    </style>
</body>
</html>
